/************************************************************************************
* FileSystemMediaLoader.cpp                                                         *
*                                                                                   *
* Copyright (C) 2011 Varuna L Amachi                                                *
*                                                                                   *
* This program is free software; you can redistribute it and/or modify              *
* it under the terms of the GNU General Public License as published by              *
* the Free Software Foundation; either version 2 of the License, or any             *
* later version.                                                                    *
*                                                                                   *
* This program is distributed in the hope that it will be useful, but               *
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY        *
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for       *
* more details. You should have received a copy of the GNU General Public           *
* License along with this program; if not, write to the Free Software Foundation,   *
* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA                       *
*                                                                                   *
*************************************************************************************/


#include "FileSystemMediaLoader.h"
#include "Constants.h"
#include "Utils.h"

#include <QDir>
#include <QList>
#include <QMessageBox>
#include <QUuid>
#include <audioproperties.h>
#include <fileref.h>
#include <tag.h>



using namespace TagLib;
using namespace Phonon;

FileSystemMediaLoader::FileSystemMediaLoader(QObject *parent) :
    QThread(parent) {
    for(int i = 0; i < Constants::NumSupportedFormats; i++) {
        m_extFilter += ("*."+Constants::FileExtentions[i]);
    }
    m_mediaList = new QList<MediaItem*>();
    m_urls = NULL;
}


FileSystemMediaLoader::~FileSystemMediaLoader() {
    clear();
    delete m_mediaList;

}


bool FileSystemMediaLoader::load(QList<QUrl>* urlList) {
    if(! this->isRunning()) {
        m_urls = urlList;
        start();
        return true;
    }
    else {
        qDebug() << "Please wait till other process finish";
        return false;
    }
}


void FileSystemMediaLoader::run() {
    QList<QString> filesToLoad;
    if(m_urls == NULL) {
        return;
    }
    foreach(QUrl url, (*m_urls)) {
        QFileInfo info(url.toLocalFile());
        if(info.exists()) {
            if(info.isDir()) {
                populateFilesPaths(info.absoluteFilePath(), filesToLoad);
            }
            else if(info.isFile()){
                if(Utils::isSupportedFile(info)) {
                    filesToLoad.append(info.absoluteFilePath());
                }
            }
        }
        else {
            // ?!?
        }
    }
    int numFiles = filesToLoad.size();
    loadingStarted(numFiles);
    for(int i = 0; i < numFiles; i++) {
        addToMediaList(new MediaSource(filesToLoad.at(i)));
        emit progress(i, filesToLoad.at(i));
    }
    emit finishedLoading(m_mediaList);
}


void FileSystemMediaLoader::clear() {
    if(m_urls != NULL) {
        m_urls->clear();
        delete m_urls;
        m_urls = NULL;
    }
    m_mediaList->clear();
}

void FileSystemMediaLoader::populateFilesPaths(QString dirPath, QList<QString>& filesToLoad) {

    QDir dir(dirPath);
    foreach(QString file, dir.entryList(m_extFilter, QDir::Files)) {
        if(Utils::isSupportedFile(QFileInfo(file))) {
            filesToLoad.append(dir.absoluteFilePath(file));
        }
    }
    foreach(QString dirName, dir.entryList(QDir::Dirs | QDir::NoDotAndDotDot)) {
        populateFilesPaths(dir.absoluteFilePath(dirName), filesToLoad);
    }
}

void FileSystemMediaLoader::addToMediaList(MediaSource *source) {
    QString uuid = QUuid().createUuid().toString();
    MediaItem* item = new MediaItem(uuid, source);
    FileRef ref = FileRef(source->fileName().toUtf8());
    item->setMetaData(TStringToQString(ref.tag()->title()),
                      TStringToQString(ref.tag()->artist()),
                      TStringToQString(ref.tag()->album()),
                      QString(ref.tag()->year()),
                      TStringToQString(ref.tag()->genre()),
                      QString(ref.tag()->track()),
                      ref.tag()->track(),
                      ref.audioProperties()->length(),
                      ref.audioProperties()->bitrate(),
                      ref.audioProperties()->sampleRate(),
                      ref.audioProperties()->channels());
    m_mediaList->append(item);
    loaded(item);
}


